package com.qf.air.interceptor;

import com.qf.air.constants.AirConstants;
import com.qf.air.util.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 维多利加
 * @Date: 2021/3/25 19:20
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {


   @Autowired
   private JedisUtils jedisUtils;

   /**
    * 前处理
    * @param request
    * @param response
    * @param handler
    * @return
    * @throws Exception
    */
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //1. 从session中查询用户信息
      //User user = (User) request.getSession().getAttribute("user");

      //从cookie中获取redis中存放对象的key

      String cookieValue = null;
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
         for (Cookie cookie : cookies) {
            if (AirConstants.USER_COOKIE.equals(cookie.getName())) {
               cookieValue = AirConstants.USER_REDIS_PREFIX + cookie.getValue();
               //存在cookie

               byte[] userKey = SerializationUtils.serialize(cookieValue);
               byte[] users = jedisUtils.get(userKey);

               System.out.println("找到" + cookieValue);

               //没有用户,或者用户以过期
               if (users != null) {
                  //2.如果登录了，return true，如果没登陆 return false
                  //为起续命
                  jedisUtils.expire(userKey, AirConstants.USER_TIMEOUT);
                  return true;
               }

            }
         }
      }
      return false;
   }
}